#include "List.h"
#define FILTER_NUM 4
// per testare i filtri
// find /usr/share/ | grep -e "/usr/share/apps*.sys*."

FileFilter filefilters[FILTER_NUM] = {
        {string("/usr/share/icons/.*"), string("icons folders frequently opened by desktop enviroinments") },
        {string("/usr/share/apps/.*icons.*"), string("icons folders frequently opened by desktop enviroinments") },
	{string("/usr/share/docs.*common.*"), string("documentation frequently browsed by desktop enviroinments") },
	{string("/usr/lib/.*"), string("system libraries usually opened by ldconfig during os boot") }
	   
};



char List::checkFile(const char *path) {

    struct stat st;
    int i,r;

    int ret = lstat(path, &st);
    

    if (ret==0) {

      for(i=0; i<FILTER_NUM;i++) {
	r=Match(path,filefilters[i].expr.c_str());
	if (r==-1) break;
	if (r==1) { 
	  //cout << "dice che " << path << " e " << filefilters[i].expr.c_str() << " matchano" << endl;
	  return 'F'; 
	}
      }
      
      if (S_ISREG(st.st_mode) || S_ISLNK(st.st_mode))
	    return 'Y';
      else if (S_ISDIR(st.st_mode))
	    return 'D';
    }
    else {
      return 'N';
    }

    
}

// Ritorna:
//  -1: Errore nella creazione del pattern
//   0: Pattern non trovato
//   1: Pattern trovato
int List::Match (const char *s, const char *regex)  {
        regex_t re;

        // Compilo un pattern regex_t associato alla mia regex
        if (regcomp(&re,regex,REG_EXTENDED|REG_NOSUB)!=0)
                return -1;

        // Applico il pattern alla stringa passata
        if (regexec(&re, s, (size_t) 0, NULL, 0))  {
                regfree(&re);
                return 0;
        }

        regfree(&re);
        return 1;
} 
